package com.serkol.driving.learning.api;

import com.serkol.bean.Result;
import com.serkol.driving.learning.ExamData;
import com.serkol.driving.learning.entity.ExamErrors;
import com.serkol.driving.learning.entity.ExamResult;
import com.serkol.driving.learning.service.ExamErrorsService;
import com.serkol.driving.learning.service.ExamResultService;
import com.serkol.driving.learning.service.QuestionBankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@RequestMapping("api/exam")
@RestController
public class ExamApiController {
    @Autowired
    private QuestionBankService questionBankService;
    @Autowired
    private ExamResultService service;
    @Autowired
    private ExamErrorsService errorsService;

    @PostMapping("/edit")
    public Result edit(@RequestBody ExamData data) {
        boolean flag = false;
        ExamResult exam = new ExamResult();
        exam.setUserId(1L);
        exam.setExamCount(data.getCount());
        exam.setExamTime(data.getTime());
        exam.setFailed(data.getFailed());
        exam.setIntegral(data.getIntegral());
        exam.setQualified(data.getQualified());
        exam.setSuccess(data.isSuccess());

        flag = service.save(exam);

        if (flag) {
            List<ExamErrors> list = new ArrayList();
            Iterator<Long> iterator = data.getFaileds().iterator();
            while (iterator.hasNext()) {
                ExamErrors errors = new ExamErrors();
                errors.setExamId(exam.getId());
                errors.setUserId(exam.getUserId());
                Long next = iterator.next();
                errors.setQuestionId(next);
                list.add(errors);
            }
            errorsService.saveBatch(list);

            return Result.ok();
        } else {
            return Result.failure();
        }

    }

    @GetMapping("/stastica")
    public Result stastica() {
        List<Integer> stastica = service.getStastica();
        return Result.ok(stastica);
    }


    @GetMapping("/getUsersStastica")
    public Result getUsersStastica() {
        List<Map<String, Object>> stastica = service.getUsersStastica();
        return Result.ok(stastica);
    }
}
